<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Sale\Controllers;


use App\Eloquent\Area;
use App\Eloquent\City;
use App\Eloquent\Province;
use App\Eloquent\Ygt\Company;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\SaleCustomer;
use App\Eloquent\Ygt\SaleCustomerRelation;
use App\Eloquent\Ygt\User;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class CustomerController extends Controller
{
    public $userId      = 209;
    public function index(){}
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['sale_user_id'=>$userId];
        $collection         = SaleCustomer::getListJoinRelation($where);
        $lists              = Func::getLetterList($collection);
//        $letterArr          = $collection->pluck('first_letter')->all();
//        $lists              = [];
//        if($letterArr)
//        {
//            $letterArr      = array_unique($letterArr);
//            sort($letterArr);
//            $listArr        = $collection->groupBy('first_letter')->toArray();
//            foreach($letterArr as $key=>$val)
//            {
//                $lists[$key]['letter']  = $val;
//                $lists[$key]['list']    = $listArr[$val];
//            }
//        }
        return $lists;
    }
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $isSubmit           = request('is_submit',0);
        if($isSubmit){
            $data                   = request()->all();
            if(!isset($data['mobile']) || !isset($data['mobile']))
            {
                xThrow( ERR_PARAMETER );
            }
            $mobile                 = $data['mobile'];
            $where                  = ['mobile'=>$mobile];
            $relationCollection     = SaleCustomer::getListJoinRelation($where);
            $isEmpty                = $relationCollection->isEmpty();
            if($isEmpty){
                $username           = $data['username'];
                $pinyin             = app('pinyin')->abbr($username);
                $firstLetter        = strtoupper(substr($pinyin,0,1));
                $letterAll          = [];
                for($i=65;$i<91;$i++){
                    $letterAll[]    = chr($i);
                }
                if(!in_Array($firstLetter,$letterAll))
                {
                    $firstLetter        = '#';
                }
                $provinceName = $cityName = $areaName = '';
                if(isset($data['province_id']))
                {
                    $provinceId     = $data['province_id'];
                    $where          = ['provinceID'=>$provinceId];
                    $collection     = Province::where($where)->first();
                    $provinceName   = $collection->province;
                }
                if(isset($data['city_id']))
                {
                    $cityId         = $data['city_id'];
                    $where          = ['cityID'=>$cityId];
                    $collection     = City::where($where)->first();
                    $cityName       = $collection->city;
                }
                if(isset($data['area_id']))
                {
                    $areaId         = $data['area_id'];
                    $where          = ['areaID'=>$areaId];
                    $collection     = Area::where($where)->first();
                    $areaName       = $collection->area;
                }
                //注册账号
                $registerResult     = false;
                exit('停了');
                $registerStatus     = $registerResult['status'];
                $registerUserId     = $registerResult['user_id'];
                $registerMessage    = $registerResult['message'];
                if($registerStatus!=1){
                    xThrow(ERR_PARAMETER, $registerMessage);
                }else{
                    $registerCompanyId  = config('sale.company_id');;
                    $where          = ['company_id'=>$registerCompanyId,'user_id'=>$registerUserId];
                    $isExist        = DepartmentUser::getInfo($where);
                    if(!$isExist)
                    {
                        $departmentUserData     = [
                            'user_id'=>$registerUserId,
                            'company_id'=>$registerCompanyId,
                            'privilege_id'=>config('sale.customer_privilege_id'),
                            'mobile'=>$mobile,
                            'truename'=>$username,
                        ];
                        DepartmentUser::insertOneData( $departmentUserData );
                    }
                }
                //添加客商的客户
                $data['user_id']        = $registerUserId;
                $data['first_letter']   = $firstLetter;
                $data['province_name']  = $provinceName;
                $data['city_name']      = $cityName;
                $data['area_name']      = $areaName;
                $fieldList              = SaleCustomer::$tableFieldList;
                $tableData              = SaleCustomer::setDataByTableField($data,$fieldList);
                $tableDataCheckResult   = SaleCustomer::checkDataByTableField($tableData,$fieldList);
                if($tableDataCheckResult !== true)
                {
                    xThrow(ERR_PARAMETER, $tableDataCheckResult);
                }
                $relationId             = SaleCustomer::edit($tableData,'id');
                if($relationId===false){
                    xThrow(ERR_UNKNOWN);
                }
                $relationData       = ['sale_user_id'=>$userId,'sale_customer_id'=>$relationId];
                $relationResult     = SaleCustomerRelation::insertOneData($relationData);
                if($relationResult === false)
                {
                    xThrow(ERR_UNKNOWN);
                }
                $result             = ['is_next'=>0,'message'=>'添加成功','list'=>[]];
            }else{
                $relationList       = $relationCollection->toArray();
                $result             = ['is_next'=>1,'message'=>'请确认','list'=>$relationList];
            }
            return $result;
        } else {
            $result                 = [];
            return $result;
        }
    }
    public function confirm()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $relationId         = request('sale_customer_id',0);
        if( !$userInfo || !$relationId){
            xThrow( ERR_PARAMETER );
        }
        $relationData       = ['sale_user_id'=>$userId,'sale_customer_id'=>$relationId];
        $existData          = SaleCustomerRelation::getList($relationData);
        $existDataResult    = $existData->isEmpty();
        if($existDataResult){
            $relationResult     = SaleCustomerRelation::insertOneData($relationData);
            if($relationResult === false)
            {
                xThrow(ERR_UNKNOWN);
            }
            $result             = ['message'=>'添加成功'];
        }else{
            $result             = ['message'=>'已经添加过了'];
        }
        return $result;
    }
    //创建订单第一步，提供默认值
    public function orderFirst()
    {
        //$userId客商的客户登录的id
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        if(!$userId)
        {
            xThrow(ERR_UNKNOWN);
        }
        $saleId             = request('sale_id',$this->userId);//客商的user_id
        $companyId          = config('sale.company_id');//客商统一默认到该厂
        $companyName        = Company::getOneValueById($companyId, 'title');
        $where              = ['user_id'=>$saleId];
        $customer           = Customer::getInfo($where);
        if(!$customer)
        {
            xThrow(ERR_UNKNOWN);
        }
        $customerId         = $customer->id;
        $result             = [
            'company_id'=>$companyId, 'company_name'=>$companyName,'customer_id'=>$customerId
        ];
        return $result;
    }
}